package com.zhugang.week01;

/**
 * @program algorithms
 * @description: removeDuplicates
 * @author: chanzhugang
 * @create: 2022/03/23 07:58
 */
public class RemoveDuplicates {

    public static void main(String[] args) {
        RemoveDuplicates removeDuplicates = new RemoveDuplicates();
        int[] nums = new int[]{1, 2, 2, 3, 4, 4, 5,};
        int length = removeDuplicates.removeDuplicates(nums);
        System.out.println(length);
    }

    /**
     * 移除有序数组中重复元素,返回数组长度
     */
    public int removeDuplicates(int[] nums) {
        // 原数组中操作，如果不在数组中，则添加
        int n = nums.length;
        int k = 0;
        for (int i = 1; i < n; i++) {
            if (nums[i] != nums[k]) {
                k++;
                nums[k] = nums[i];
            }
        }
        return k + 1;
    }
}